package com.atguigu.java8.datetime;

import org.junit.Test;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestSimpleDateFormat {

    @Test
    public void test1() throws ExecutionException, InterruptedException {
        // SimpleDateFormat线程安全问题
        // 异常信息：java.util.concurrent.ExecutionException: java.lang.NumberFormatException: multiple points
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Callable<Date> callable = () -> dateFormat.parse("2024-03-08");

        List<Future<Date>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            futures.add(executorService.submit(callable));
        }
        for (Future<Date> future : futures) {
            System.out.println(future.get());
        }
        executorService.shutdown();
    }

    @Test
    public void test2() throws ExecutionException, InterruptedException {
        // 解决SimpleDateFormat线程安全问题
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Callable<Date> callable = () -> DateFormatThreadLocal.convert("2024-03-08");

        List<Future<Date>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            futures.add(executorService.submit(callable));
        }
        for (Future<Date> future : futures) {
            System.out.println(future.get());
        }
        executorService.shutdown();
    }

    @Test
    public void test3() throws ExecutionException, InterruptedException {
        // 使用新时间API替换SimpleDateFormat
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Callable<LocalDate> callable = () -> LocalDate.parse("2024-03-08", dateTimeFormatter);

        List<Future<LocalDate>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            futures.add(executorService.submit(callable));
        }
        for (Future<LocalDate> future : futures) {
            System.out.println(future.get());
        }
        executorService.shutdown();
    }

}
